package com.shaonianyou.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;

/**
 * 
 * @author Empty
 *
 */
@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {
	
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String loginPage(HttpServletRequest request, Model model) {

		return "login";
	}

	@RequestMapping(value = "/getCode", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getCode(String idCard, String mobile) {
		Map<String, Object> param = Maps.newHashMap();
		param.put("idcard", idCard);
		param.put("mobile", mobile);
		return doPost("/sendCode", param);
	}

	/**
	 * 登录
	 * 
	 * @param idCard
	 * @param mobile
	 * @param code
	 * @param openid
	 * @param request
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(String idCard, String mobile, String code, String openid, HttpServletRequest request,
			Model model) {
		String url = "login";
		Map<String, Object> param = Maps.newHashMap();
		param.put("idcard", idCard);
		param.put("mobile", mobile);
		param.put("code", code);
		param.put("openid", openid);
		Map<String, Object> resultMap = doPost("/login", param);
		if (resultMap.get("code").equals("0")) {
			Map<String, Object> userInfoMap = (Map<String, Object>) resultMap.get("data");
			request.getSession().setAttribute("custId", userInfoMap.get("custId"));
			url = "index";
		} else {
			model.addAttribute("openid", openid);
			model.addAttribute("msg", resultMap.get("message"));
		}
		return url;
	}

	/**
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request, Model model) {
		Map<String, Object> param = Maps.newHashMap();
		param.put("custId", request.getSession().getAttribute("custId"));
		doPost("/loginOut", param);
		request.getSession().removeAttribute("custId");
		return "logout";
	}

}
